package com.zb.service.impl;

import com.zb.entity.AccounLoginInfo;
import com.zb.entity.ZjCustomerWxAuthor;
import com.zb.exception.WxException;
import com.zb.redis.RedisUtil;
import com.zb.service.WxPublicNoAuthorizeThirdService;
import com.zb.service.ZjCustomerWxAuthorService;
import com.zb.wx.WxCacheKeyConstant;
import com.zb.wx.WxPublicNoApiAuthorizeConstant;
import com.zb.wx.WxSecretKeyConstant;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author WEN
 * @Date 2024/2/28 0028
 **/
@Log4j2
@Service
public class WxPublicNoAuthorizeThirdServiceImpl implements WxPublicNoAuthorizeThirdService {
    @Resource
    private ZjCustomerWxAuthorService customerWxAuthorService;

    // 获取第三方平台授权
    @Override
    public String getAuthorizePage(AccounLoginInfo loginInfo, String uuid) throws WxException {
        // 重写向路径
        String redirectUri = WxPublicNoApiAuthorizeConstant.AUTHOR_REDIRECT_URI.replaceAll("uuid", uuid);
        // 获取授权页面组件连接
        String url = WxPublicNoApiAuthorizeConstant.AUTHOR_COMPONENT_LOGIN_PAGE_API.replaceAll("COMPONENT_APPID", WxSecretKeyConstant.APP_ID)
                .replaceAll("PRE_AUTH_CODE", WxHttpClientUtil.getPreAuthCode())
                .replaceAll("REDIRECT_URI", redirectUri)
                .replaceAll("AUTH_TYPE","")
                ;
        // 缓存websocket标识uuid
        RedisUtil.setCache(WxCacheKeyConstant.WX_AUTHOR_WEBSOCKET_UUID + uuid, loginInfo.getCustAccId());
        return url;
    }

    // 保存商家取消微信授权
    @Override
    public void cancelCustomerWxAuthor(Long custAccId) {
        ZjCustomerWxAuthor wxAuthor = customerWxAuthorService.getAuthorizerById(custAccId);
        // 调取微信接口
        WxHttpClientUtil.publicNoUnbindAuthorThird(custAccId, wxAuthor.getOpenAppid(), wxAuthor.getAuthorizerAppid());
        // 取消授权
        customerWxAuthorService.updateCancelAuthorById(custAccId);
    }
}
